/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jeesite.modules.ajz.web;

import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.company.api.QYOauthAPI;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.ajz.entity.*;
import com.jeesite.modules.ajz.service.AjzCompanyInfoService;
import com.jeesite.modules.ajz.service.AjzHouseInfoService;
import com.jeesite.modules.ajz.service.AjzRecordProcessService;
import com.jeesite.modules.ajz.service.AjzStoreInfoService;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.utils.PicToWord;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jeesite.modules.sys.utils.Timestamp.TIMESTAMP;

/**
 * 门店区域划分表Controller
 *
 * @author cww
 * @version 2018-12-29
 */
@Controller
@RequestMapping(value = "${adminPath}/ajz/ajzBaseinfo")
public class AjzBaseinfoController extends BaseController {

    @Autowired
    private AjzCompanyInfoService ajzCompanyInfoService;

    @Autowired
    private AjzRecordProcessService ajzRecordProcessService;

    @Autowired
    private AjzStoreInfoService ajzStoreInfoService;

    @Autowired
    private AjzHouseInfoService ajzHouseInfoService;



    /**
     * 跳转到首页
     * @param request
     * @param response
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping({"index"})
    public String index( HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);
        String userId = QyConfigUtil.getUserId(request,response);

        if (StringUtils.isEmpty(userId)) {
            QYOauthAPI qyOauthAPI = QyConfigUtil.getQYOauthAPI();
            String oauthPageUrl = qyOauthAPI.getOauthPageUrl(request.getRequestURL().toString(),OauthScope.SNSAPI_BASE,"1");
            oauthPageUrl = URLDecoder.decode(oauthPageUrl, "utf-8");
            ServletUtils.redirectUrl(request, response, oauthPageUrl);
        }

        String type = request.getParameter("type");
        //统计页面
        if ("statistics".equals(type)) {
            return "modules/ajz/mobile/index_statistics";
        }
        //图标页面
        if ("map".equals(type)) {
            return "modules/ajz/mobile/index_map";
        }
        //地图页面
        if ("chart".equals(type)) {
            return "modules/ajz/mobile/index_chart";
        }
        return "modules/ajz/mobile/index";
    }

    //通过搜索框搜索
    /**
     *  通过搜索框搜索
     */
    @RequestMapping({"search"})
    public Map<?, ?> search(@Param("name")String name){
        Map<Object,Object> map = new HashMap<Object, Object>();
        //获取对应的id与名称
        map.putAll(Dearch4Date(ajzCompanyInfoService.findListByName(name)));
        map.putAll(Dearch4Date(ajzStoreInfoService.findListByName(name)));
        map.putAll(Dearch4Date(ajzHouseInfoService.findListByAddr(name)));
        return map;
    }


    /**
     * 搜索功能数据处理
     * @param entitys
     * @param <T>
     * @return id,enterpriseName
     */
    public static <T> Map<?,?> Dearch4Date(List<T> entitys){
        Map<Object, Object> map = new HashMap<Object,Object>();
        String value1 = "";
        String value2 = "";
        if(entitys!=null&&entitys.size()>0){
            for(T entity:entitys){
                try {
                    //获取类名
                    String packageName = entity.getClass().getName();
                    String className = packageName.substring(packageName.lastIndexOf(".") + 1);
                    //获取id
                    value1 = entity.getClass().getMethod("getId").invoke(entity).toString();
                    //获取户外招牌/营业执照名/地址
                    if("AjzHouseInfo".equals(className)){
                        value2 = entity.getClass().getMethod("getAddr").invoke(entity).toString();
                    }else{
                        //获取营业执照名
                        value2 = entity.getClass().getMethod("getEnterpriseName").invoke(entity).toString();
                    }
                    //返回map
                    StringBuffer key = new StringBuffer(value1+"|"+value2);
                    map.put(key.toString(),className);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }

        return map;
    }




    //点击查询
    @RequestMapping({"searchName"})
    public String searchName(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        Map<String, List> map = new HashMap<String, List>();
//        List list = new ArrayList<>();
        AjzRecordProcess ajzRecordProcess = new AjzRecordProcess();

        //查询企业的基本信息
        String id = request.getParameter("id");

        String user = request.getParameter("user");
        if(StringUtils.isNotBlank(user)){
            model.addAttribute("user",user);
        }else {
            model.addAttribute("user","system");
        }

        //获取隐患类型为aqsc的企业
        AjzCompanyInfo companyInfo = new AjzCompanyInfo();
        AjzRecord ajzRecord = new AjzRecord();
        ajzRecord.setTableType("ajz"); //随便赋值一个,获取record为空,否则会查询出多条记录
        companyInfo.setAjzRecord(ajzRecord);
        companyInfo.setId(id);

        AjzCompanyInfo ajzCompanyInfo = ajzCompanyInfoService.get(companyInfo);
        model.addAttribute("ajzCompanyInfo",ajzCompanyInfo);


        AjzStoreInfo storeInfo = new AjzStoreInfo();
        storeInfo.setAjzRecord(ajzRecord);
        storeInfo.setId(id);
        AjzStoreInfo ajzStoreInfo = ajzStoreInfoService.get(storeInfo);
        model.addAttribute("ajzStoreInfo",ajzStoreInfo);

        AjzHouseInfo houseInfo = new AjzHouseInfo();
        houseInfo.setAjzRecord(ajzRecord);
        houseInfo.setId(id);
        AjzHouseInfo ajzHouseInfo = ajzHouseInfoService.get(houseInfo);
        model.addAttribute("ajzHouseInfo",ajzHouseInfo);
        String skip = "";
        //判断搜索框的值，如果企业的实体类为空，则表示获取到了其他类型的企业信息，修改跳转地址，然后返回
        if (ajzCompanyInfo != null) {
            //检查记录
            ajzRecordProcess.setBaseType("company");

            ajzRecordProcess.setAjzCompanyInfo(ajzCompanyInfo);
            skip = "modules/ajz/mobile/query_aqsc";
        } else if (ajzStoreInfo != null) {
            ajzRecordProcess.setBaseType("store");
            ajzRecordProcess.setAjzStoreInfo(ajzStoreInfo);
            skip = "modules/ajz/mobile/query_store";
        }else if(ajzHouseInfo != null){
            ajzRecordProcess.setBaseType("house");
            ajzRecordProcess.setAjzHouseInfo(ajzHouseInfo);
            skip = "modules/ajz/mobile/query_house";
        }
        List<AjzRecordProcess> ajzRecordProcessList = ajzRecordProcessService.findList(ajzRecordProcess);
        if(ajzRecordProcessList.size()>0){
            map.put("第一轮检查",ajzRecordProcessList);
        }



        //查询检查记录信息

//        //取字典cycle_manager中的安全生产轮次
//        List<DictData> list = DictUtils.getDictList("cycle_aqsc");
//
//        //对取值进行排序
//        Collections.sort(list, new Comparator<DictData>(){
//            @Override
//            public int compare(DictData o1, DictData o2) {
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                try {
//                    Date dt1 = format.parse(o1.getDictValue().split("~")[0]);
//                    Date dt2 = format.parse(o2.getDictValue().split("~")[0]);
//                    if (dt1.getTime() > dt2.getTime()) {
//                        return 1;
//                    }else{
//                        return -1;
//                    }
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                return 0;
//            }
//        });
//
//        for (DictData cycle :
//                list) {
//            String lable = cycle.getDictLabel();
//            //获取轮次时间
//            String cycleTime = cycle.getDictValue();
//
//            //检查记录
//            AjzRecordProcess ajzRecordProcess = new AjzRecordProcess();
//            ajzRecordProcess.setBaseType("company");
//            ajzRecordProcess.setTableType("ajz_aqsc");
//            ajzRecordProcess.setAjzCompanyInfo(ajzCompanyInfo);
//            ajzRecordProcess.setCreateDate_between(cycleTime);
//
//            //查询对应时间段的检查记录
//            ajzRecordProcess.setPage(new Page<>(request, response));
//            Page<AjzRecordProcess> page = ajzRecordProcessService.findPage(ajzRecordProcess);
//            if (page.getList().size() > 0) {
//                map.put(lable+"||"+cycleTime+"",page.getList());
//            }
//        }

        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);
        model.addAttribute("records",map);
        return skip;
    }

    @Autowired
    OfficeService officeService;

    @RequestMapping({"addBaseInfo"})
    public String addBaseInfo(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        String userId = CookieUtils.getCookie(request, "userId");

        if(StringUtils.isBlank(userId)){
            userId = "system";
        }

        //获得微信jssdk签名等
        QyConfigUtil.getJSSDKSign(request,model);

        model.addAttribute("userId",userId);

        //获取机构名称
        //根据人员获取office的父级code
//        User user = UserUtils.get(userId);
//        Employee employee = (Employee) user.getRefObj();
//        employee.getOffice().getParentCode();



        //或者默认一个父级机构的名称
        Office office = new Office();
        office.setParentCode(Global.getConfig("ajz.add.officeCode"));
        List<Office> officeList = officeService.findList(office);
        model.addAttribute("officeList",officeList);
        //时间戳
        model.addAttribute("Timestamp", TIMESTAMP);

        return "modules/ajz/mobile/add_baseinfo";
    }



    @RequestMapping({"synchSingle"})
    public String synchSingle(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        model.addAttribute("userId","");
        return "modules/ajz/fw/staff";
    }


    //主页页面跳转至 企业页面
    @RequestMapping({"qyIndex"})
    public String qyIndex( HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        model.addAttribute("userId",request.getParameter("userId"));
        model.addAttribute("openId","");
        return "modules/ajz/mobile/qyIndex";
    }



    //营业执照识别
    @RequestMapping({"getBLiscenseMsg"})
    @ResponseBody
    public String getBLiscenseMsg(HttpServletRequest request) throws InterruptedException {
        //获取图片
        String pic = PicToWord.getBLiscenseMsg(request);
        return pic;
    }



//    //识别营业执照返回执照信息
//    @RequestMapping(value = "getBLiscenseMsg")
//    @ResponseBody
//    public String getBLiscenseMsg(HttpServletRequest request) {
//        System.out.println("提取营业执照结果:");
//        String pic = request.getParameter("pic");
//        //创建保存在文件管理器中的文件路径
//        String filePath =  Global.getUserfilesBaseDir("企业" + File.separator + "营业和户外照片" + File.separator
//                + DateUtils.getYear() + File.separator
//                + DateUtils.getMonth() + File.separator
//                + DateUtils.getDay() + File.separator);
//        //创建保存数据库的图片路径
//        String savePath = request.getContextPath() + File.separator +"userfiles"+ File.separator +  "企业" + File.separator + "营业和户外照片" + File.separator
//                + DateUtils.getYear() + File.separator
//                + DateUtils.getMonth() + File.separator
//                + DateUtils.getDay() + File.separator;
//        FileUtils.createDirectory(filePath);
//
//        if (!StringUtils.isBlank(pic)) {
//
//            pic = DloadImgUtil.downloadMedias(QyConfigUtil.getAccessToken(),"", pic,request.getContextPath()+ File.separator +"userfiles", Global.getUserfilesBaseDir(""));
//            pic = pic.split("/")[1];
//        }
//        pic = Global.getUserfilesBaseDir("")+pic;
//        String picMsg = PicToWord.getBussinessLicenseMsg(pic);
//        System.out.println("提取营业执照结果:"+picMsg);
//        try {
//            DeleteFile t = new DeleteFile();
//            t.delete(pic);                  //删除照片
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
//        return picMsg;
//    }

    //根据类型获取机构
    @RequestMapping({"getOfficeListByBaseType"})
    public List<Office> getOfficeListByBaseType(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        String type = request.getParameter("baseType");
        Office office = new Office();
        switch (type){
            case "company":office.setParentCode(Global.getConfig("ajz.add.officeCode"));break;
            case "store":office.setParentCode(Global.getConfig("ajz.add.store.officeCode"));break;
            case "house":office.setParentCode(Global.getConfig("ajz.add.house.officeCode"));break;  //TODO
            default:office.setParentCode(Global.getConfig("ajz.add.officeCode"));
        }
        List<Office> officeList = officeService.findList(office);
        return officeList;
    }

}